﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace RapidDownloader.Model.Services.RapidShare
{
    public sealed partial class RapidShareDownloadProvider : IDownloadProvider
    {
        #region Public Methods

        public void CheckFiles(IEnumerable<DownloadFile> files)
        {
            var rapidShareFiles = files.OfType<RapidShareFile>().ToArray();
            if (rapidShareFiles.Length == 0)
                return;

            var fileIdsBuilder = new StringBuilder();
            var filesBuilder = new StringBuilder();

            rapidShareFiles.Run(file =>
                                    {
                                        fileIdsBuilder.AppendFormat("{0},", file.Id);
                                        filesBuilder.AppendFormat("{0},", file.FileName);
                                    });

            fileIdsBuilder.Remove(fileIdsBuilder.Length - 1, 1);
            filesBuilder.Remove(filesBuilder.Length - 1, 1);

            var response = WebHelper.DownloadString(string.Format("http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=checkfiles_v1&files={0}&filenames={1}&incmd5=1", fileIdsBuilder, filesBuilder));
            if (!response.StartsWith("ERROR") && response.Length > 0)
            {
                var entries = response.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                entries.Run(entry =>
                                {
                                    var entryResponseParts = entry.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (entryResponseParts.Length > 1)
                                    {
                                        var key = string.Concat("RS:", entryResponseParts[0], entryResponseParts[1]);
                                        var rapidShareFile = rapidShareFiles.FirstOrDefault(rsf => rsf.Key == key);
                                        if (rapidShareFile != null)
                                            rapidShareFile.UpdateServerStatus(entryResponseParts.Skip(1).ToArray());
                                        else
                                            Debug.Assert(false, "Could not find file again from checkfiles call.");
                                    }
                                });
            }
        }

        public IEnumerable<DownloadFile> GetFiles(string text)
        {
            return Regex.Matches(text, "https?://(?:www.)?rapidshare.com/files/(\\d+)/([^ \r\n\"]+)").Cast<Match>().Select(m => new RapidShareFile(m.Groups[1].Value, NoHtml(m.Groups[2].Value)));
        }

        #endregion

        #region Class Methods

        private static string NoHtml(string value)
        {
            return value.EndsWith(".html") ? value.Substring(0, value.Length - 5) : value;
        }

        #endregion
    }
}